pub mod api;
pub mod controller;
pub mod model;
pub mod router;

use salvo::prelude::*;
use std::sync::Arc;
use tracing::info;
use utils::rpc::RpcClientManager;

use self::router::api_router;
use crate::rpc::client::InfraRpcClient;

/// 构建API路由器，包含所有API相关的路由和中间件
pub async fn build_api_router(
    rpc_manager: Arc<RpcClientManager>,
    infra_rpc_client: Arc<InfraRpcClient>,
) -> Router {
    info!("构建 Infra API 路由器");
    
    // 创建API路由器
    let router = api_router()
        .hoop(middleware::add_rpc_clients(rpc_manager, infra_rpc_client));

    info!("Infra API 路由器构建完成");
    router
}

/// 中间件模块
pub mod middleware {
    use super::*;
    use salvo::prelude::*;
    use std::sync::Arc;
    use utils::rpc::RpcClientManager;
    use crate::rpc::client::InfraRpcClient;

    /// 添加RPC客户端到请求上下文的中间件
    #[handler]
    pub async fn add_rpc_clients(
        req: &mut Request,
        depot: &mut Depot,
        rpc_manager: Arc<RpcClientManager>,
        infra_rpc_client: Arc<InfraRpcClient>,
    ) {
        // 将RPC客户端添加到请求扩展中
        req.extensions_mut().insert(rpc_manager);
        req.extensions_mut().insert(infra_rpc_client);
    }
}